package com.example.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static boolean isLeapYear(int year) {
        //if((year%4==0 && year%100!=0) || year%400==0)
        //    return true;
        //return false;
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }

    public static int getMaxDays(int year, int month) {
        if (month < 1 || month > 12)
            return -1;//错误的提示
        int days = 0;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days = 31;
                break;
            case 2:
                //days=28;
                //if(isLeapYear(year))
                //    days++;
                days = isLeapYear(year) ? 29 : 28;
                break;
            default:
                days = 30;
                break;
        }
        return days;
    }

    /**
     * 某年某月某日是周几
     *
     * @param year
     * @param month
     * @param date
     * @return
     */
    public static int getDayOfWeek(int year, int month, int date) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, date);

        return cal.get(Calendar.DAY_OF_WEEK) - 1;//周日是数字0
    }

    //封装日期的格式
    public static String format(Date date, String partten) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(partten);

        return sdf.format(date);
    }

    //将字符串解析成date类型
    public static Date parse(String data, String partten) {
        if (data == null || data.trim().length() == 0) {
            return null;
            //trim  将两边多余的字符串删除
        }

        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(partten);
        try {
            date = sdf.parse(data);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

//    public static void main(String[] args) {
//       String date=format(new Date(),"yyyy/MM/dd");
//        System.out.println(date);
//    }

}
